package com.cloudcross.ssp.web.advertiser.main;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Md5Tool;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.AccountResources;
import com.cloudcross.ssp.model.Advertiser;
import com.cloudcross.ssp.model.Resources;
import com.cloudcross.ssp.model.UserLogin;
import com.cloudcross.ssp.service.IAccountService;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.IOperatorService;
import com.cloudcross.ssp.service.IResourcesService;
import com.cloudcross.ssp.service.IUserLoginService;

/**
 * 广告主端权限管理
 * 代理商才有的权限，代理商能创建两种账号：1.代理商子账号（不关联广告主）；2.广告主账号（关联广告主）
 * 修改人：wuqiang.du
 * 修改时间：2016-03-11
 */
@Controller
@RequestMapping("/advertiser/main/authority")
public class AuthorityController extends SimpleController{
	
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	
	@Autowired
	protected IAccountService accountService;
	
	@Autowired
	protected IUserLoginService userLoginService;
	
	@Autowired
	protected IOperatorService operatorService;
	
	@Autowired
	protected IResourcesService resourcesService;
	
	@Autowired
	protected IAdvertiserService advertiserService;
	

	/**
	 * 重定向：重新向url发请求
	 * @return 目标url
	 */
	@RequestMapping
	public String index(){
		return redirect(page("list"));
	}
	/**
	 * 广告主账号列表页
	 * @param model
	 * @param page
	 * @param searchValue 查询条件，根据姓名查询，要转码
	 * @return
	 * 查询条件：sys_type = 3且不是当前登录用户
	 */
	@RequestMapping("list")
	public String list(Model model,@RequestParam(defaultValue="1") int page,String searchValue){
		Map<String,Object>condition = new HashMap<String,Object>();//存放查询条件
		condition.put("sysType", 3);//代理商系统sys_type = 3
		//处理查询条件
		if(StringUtils.isNotBlank(searchValue)){
			condition.put("searchVal", "%"+searchValue+"%");
			model.addAttribute("searchValue", searchValue);
		}
		
		//根据当前登录用户获取代理商ID
		Account loginAccount = getLoginUser();
		condition.put("agentId", loginAccount.getAgentId());
		condition.put("accountId", loginAccount.getId());
		int totalRow = this.accountService.queryAccountCountByCondition(condition);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		List<Account> accountList = accountService.queryAccountByCondition(condition, pager);
		//循环获取查询到账号的登录时间；保存到对象的creatTime字段中
		for (int i = 0; i < accountList.size(); i++) {
			UserLogin login = userLoginService.queryUserLoginById(accountList.get(i).getId());
			//查询到的用户可能从未登录过系统，所以这里要判断一下，避免空指针异常！
			if (login == null) {
				continue;
			}
			accountList.get(i).setCreateTime(login.getLoginTime());
		}
		model.addAttribute("accountList",accountList);
		model.addAttribute("pager",pager);
		return page("list");
	}
	
	/**
	 * 创建创建账号页面：1.子账号；2广告主账号   区别：是否关联广告主
	 * @param model
	 * @return
	 */
	@RequestMapping("/create")
	public String create(Model model){
		Account account = getLoginUser();
		//该账号做具有的所有的资源
		List<Resources> parentResList = resourcesService.findAllResourcesByAccountId(account.getId());
		model.addAttribute("agentId",account.getAgentId());//要传代理商的Id到页面上去！
		model.addAttribute("parentResList",parentResList);
		return page("create");
	}
	
	/**
	 * 
	 * @param model
	 * @param t
	 * @param authority
	 * @param ensurePassword
	 * @return
	 */
	@RequestMapping("/save")
	public String save(Model model,@ModelAttribute("form") Account t,
					@RequestParam(value = "authority", defaultValue = "") String authority,
					@RequestParam(value = "ensurePassword", defaultValue = "") String ensurePassword){
		Account acc = new Account();
		String password = t.getPassword();
		Account account = getLoginUser();
		
		//根据t.getId()是否为0来判断是新增账号还是修改账号
		if ((t.getId()) == 0) {//新增账号
			//创建时，一些信息要与当前用户保持一致
			acc.setAgentId(account.getAgentId());
			acc.setOperatorId(account.getOperatorId());
			acc.setSysType(account.getSysType());
			acc.setType(account.getType());//1或5
			acc.setPassword(Md5Tool.getMd5(password));
			acc.setAccountName(t.getAccountName());
			acc.setState(t.getState());
			acc.setTel(t.getTel());
			acc.setRealName(t.getRealName());
			acc.setCreateTime(new Date());
			acc.setLonginUrl(account.getLonginUrl());
			acc.setIconPathurl(account.getIconPathurl());
			//根据t.getAdvertiserId()来判断是创建代理商子账号还是广告主账号
			if(t.getAdvertiserId()==null){//没有绑定广告主，代理商小账号
				acc.setDescription(account.getDescription()+"（小）");
				acc.setAdvertiserId(new Long(0));
				accountService.insertAccount(acc);
			}else{//给广告主创建的账号
				Advertiser advertiserName = advertiserService.findById(t.getAdvertiserId());
				acc.setDescription(advertiserName.getName());//账号的描述存放要关联的广告主的名字
				acc.setAdvertiserId(t.getAdvertiserId());
				accountService.insertAccount(acc);
			}
			//处理有关权限的信息,删除已有权限信息，添加新权限信息
			if(authority != null && !authority.equals("")){
				List<Long> autList = new ArrayList<Long>();
				String[] aut = authority.split(",");
				for(int i=0;i < aut.length;i++){
					autList.add(Long.parseLong(aut[i]));
				}
				resourcesService.addAccountResourcess(new Long(acc.getId()),autList);
			}
		}else{//修改账号信息，账号不能改
			if(StringUtils.isNotBlank(password)){//为空不修改密码
				acc.setPassword(Md5Tool.getMd5(password));
			}
			String advName = "";
			if(t.getAdvertiserId() != null && t.getAdvertiserId() != 0){
				Advertiser advertiserName = advertiserService.findById(t.getAdvertiserId());
				advName =  advertiserName.getName();
			}else{
				advName = account.getDescription()+"（小）";
			}
			acc.setDescription(advName);//账号的描述存放要关联的广告主的名字
			acc.setId(t.getId());
			acc.setRealName(t.getRealName());
			acc.setTel(t.getTel());
			acc.setState(t.getState());
			//Account accountBef = accountService.queryAccountById((long) acc.getId());//修改前的账号
			//修改时，accountId不变，不管是否有advertiserId,把最新的advertiserId更新到advertiserId即可
			acc.setAdvertiserId(t.getAdvertiserId());
			accountService.updateAccount(acc);
			 //权限修改分为四种情况：（0>0,0>1,1>0,1>1）
			 //先得到修改前的权限
			 List<Resources> resources = resourcesService.findAllResourcesByAccountId(acc.getId());
			if(StringUtils.isNotBlank(authority)){//修改后有权限，不管以前没有没，先删除以前的，再添加新权限
				List<Long> autList = new ArrayList<Long>();
				String[] aut = authority.split(",");
				for(int i=0;i < aut.length;i++){
					autList.add(Long.parseLong(aut[i]));
				}
				resourcesService.addAccountResourcess(acc.getId(),autList);
			}else{//修改后无权限
				if(resources.size() > 0){//修改前有权限，删除以前的权限
					 this.resourcesService.deleteAccountResourcess(acc.getId());
					 }
				}
			}
			 
		// 跳转到管理页面。
		return redirect(page("list"));
	}
	
	/**
	 * 到权限管理账号编辑页面  数据：1.当前账号信息系；2.账号对应的权限信息; 3.当前账号创建的所有广告主
	 * @param model
	 * @param accountId
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(Model model, @RequestParam long accountId) {
		//当前账号信息
		Account account = accountService.queryAccountById(accountId);
		String name = "";
		if(account.getAdvertiserId() > 0){
			Advertiser advertiser = advertiserService.findById(account.getAdvertiserId());
			name = advertiser.getName();
		}
		model.addAttribute("name",name);
		//当前账号的权限信息
		String authority = "";
		List<AccountResources> resources = resourcesService.queryResourcesByAccountId(accountId);
		//查询resourceId，拼接字符长，逗号分隔（a1,a2,...,an）
		if(resources.size()>0){//resources<=0说明没有添加权限信息
			for(int i=0;i<resources.size()-1;i++){
				//循环取出resources中的id
				authority = authority + resources.get(i).getResourceId().toString() + ",";
			}
			authority = authority + resources.get(resources.size()-1).getResourceId().toString() ;
		}
		
		//取登录账号对象
		Account parentAcc = getLoginUser();
		//父账号做具有的所有的资源
		List<Resources> parentResList = resourcesService.findAllResourcesByAccountId(parentAcc.getId());
		
		model.addAttribute("parentResList",parentResList);
		model.addAttribute("authority",authority);
		model.addAttribute("account", account);
		return page("edit");
	}
	
	/**
	 * 开启
	 * 权限管理：1（开启），0（停止）
	 * disable(1), enable(0),
	 * @param id
	 * @return
	 */
	@RequestMapping("enable")
	@ResponseBody
	public  String enable(Long[] id){
		if (ArrayUtils.isNotEmpty(id)) {
			accountService.updateState(LangUtil.array2List(id),Status.disable.value);
		}
		return OK;
	}
	
	/**
	 * 暂停
	 * 权限管理：1（开启），0（停止）
	 * disable(1), enable(0),
	 * @param id
	 * @return
	 */
	@RequestMapping("disable")
	@ResponseBody
	public  String disable(Long[] id){
		if (ArrayUtils.isNotEmpty(id)) {
			accountService.updateState(LangUtil.array2List(id),Status.enable.value);
		}
		return OK;
	}
	/**
	 * 跳转到个人信息修改页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/loginperson")
	public String personInfEdit(Model model){
		Account account = getLoginUser();
		model.addAttribute("account",account);
		return page("loginperson");
	}
	
	/**
	 * 个人信息修改的保存操作！！
	 * @param model
	 * @param t
	 * @param ensurePassword
	 * @return 保存操作成功要跳转回login页面，重新输入密码后才能再次进入系统
	 */
	@RequestMapping("/saveloginperson")
	public String saveloginperson(Model model,@ModelAttribute("form") Account t,
					@RequestParam(value = "ensurePassword", defaultValue = "") String ensurePassword){
		Account acc = new Account();
		String password = t.getPassword();
		acc.setId(t.getId());
		if (StringUtils.isNotBlank(password)) {
			t.setPassword(Md5Tool.getMd5(password));
		}
		acc.setRealName(t.getRealName());
		acc.setTel(t.getTel());
		acc.setState(t.getState());
		
		accountService.updateAccount(acc);
		if(StringUtils.isNotBlank(password)){
			return "/login";
		}else{
			return "/advertiser/main/dashboard";
		}
		
	}
	
	@RequestMapping("isExist")
	public @ResponseBody String isExist(Model model,
			@RequestParam(defaultValue = "") String accountName
			) {
		String success = "";
		Account account = accountService.querySingleAccount(accountName);
		if(account!=null){
			model.addAttribute("isExist", new Long(1));
			success = "YES";
		}else {
			model.addAttribute("isExist", new Long(0));
			success = "NO";
		}
		return success;
	}
	
	/**
	 * 账号信息导出
	 * @param response
	 * @param searchValue
	 */
	@RequestMapping("/exportDataReportExcel")
	public void exportDataReportExcel(HttpServletResponse response,String searchValue){
		Map<String,Object>condition = new HashMap<String,Object>();//存放查询条件
		
		//处理查询条件
		String value = "";
		if(StringUtils.isNotBlank(searchValue)){
			try {
				value = new String(searchValue.trim().getBytes("ISO-8859-1"),"UTF-8");
				condition.put("searchVal", "%"+value+"%");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		//根据当前登录用户获取代理商ID
		Account loginAccount = getLoginUser();
		condition.put("agentId", loginAccount.getAgentId());
		condition.put("accountName", loginAccount.getAccountName());
		
		List<Account> accountList = accountService.queryAccountByCondition(condition, null);
		for (int i = 0; i < accountList.size(); i++) {
			UserLogin login = userLoginService.queryUserLoginById(accountList.get(i).getId());
			//对于没有登过系统的账号，显示创建时间
			if (login == null) {
				continue;
			}
			accountList.get(i).setCreateTime(login.getLoginTime());
		}
		condition.put("dataList", accountList);
		
		response.reset();
		// Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
		response.setContentType("application/vnd.ms-excel;charset=utf8");
		// 设置excel文件名称
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "account" + df2.format(new Date());
		response.setHeader("Content-Disposition", "attachment;filename="+ fileName + ".xls");
		// 需要对excel的列和行的总数进行指定
		int column = 7;
		condition.put("dataSize", (accountList.size() + 100));
		condition.put("column", column);
	
		condition.put("accountList", "账号列表");
		String excelTemplate = templateProcessor.processTemplate("excel/dataAccount.ftl", condition);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

